#include "server.h"

//给mysql建立连接
//-1连接错误，0为连接正常
int server_mysql_init(net_disk_t *net_disk){

    net_disk->mysql = mysql_init(NULL);
     if (net_disk->mysql == NULL) {
     fprintf(stderr, "mysql_init() failed\n");
     exit(1);
 }

    if (!mysql_real_connect(net_disk->mysql, "localhost", "root", 
                            "123456", "user_file", 0, NULL, 0)) {
        printf( "%s\n", mysql_error(net_disk->mysql));
        return -1;
    }
    return 0;
}

//获取res结果集
MYSQL_RES *mysql_get_res(MYSQL *msql,char *state){

    MYSQL_RES *result;
    if (mysql_query(msql, state)) {
        return (MYSQL_RES*)(-1);
    }

    result = mysql_store_result(msql);
    return result;
}

//获取查询结果是否存在
//返回是否存在的标记
//-1不存在，0及以上代表查询结果行数
int mysql_select_file_is_exist(MYSQL *msql,char *state){

    MYSQL_RES *res = mysql_get_res(msql, state);

    if(res == (MYSQL_RES*)(-1)){
        return -1;
    }
    int nums = mysql_num_rows(res);
    mysql_free_result(res);

    return nums;
}

//获取单行查询结果
//通过查询语句将查询到的单行结果存入传入的字符串数组
int mysql_select_get_one_row(MYSQL *msql,char *state,char (*str_arr)[1024]){

    MYSQL_RES *res = mysql_get_res(msql, state);
    if(res == (MYSQL_RES *)(-1)){
        return -1;
    }

    if((mysql_num_rows(res)) != 1){
        return 0;
    }

    int nums = mysql_num_fields(res);
    MYSQL_ROW row = mysql_fetch_row(res);
    for(int i = 0; i < nums; i++){
        strcpy(str_arr[i], row[i]);
    }

    mysql_free_result(res);
    return 1;
}

//获取单个查询结果
//通过查询语句将查询到的单行单列结果存入字符串
int mysql_select_get_one_str(MYSQL *msql,char *state,char *str){

    MYSQL_RES *res = mysql_get_res(msql, state);
    if(res == (MYSQL_RES*)(-1)){
        return -1;
    }

    if(mysql_num_rows(res) != 1){
        return 0;
    }

    MYSQL_ROW row;
    row = mysql_fetch_row(res);
    strcpy(str, row[0]);

    mysql_free_result(res);
    return 1;
}

